package com.health.controller;

import com.health.pojo.Users;
import com.health.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/login")
public class UserServlet extends HttpServlet {

    UserService userService = new UserService();

    /**
     * 用户登录
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String checkCode = (String) request.getSession().getAttribute("checkCode");
        String checkCodeForUser = request.getParameter("checkCode");
        String userAccount = request.getParameter("username");
        String userPassword = request.getParameter("password");
        Users user = new Users(userAccount, userPassword);
        int loginStatus = userService.login(checkCode, checkCodeForUser, user);
        if (loginStatus == 0) {
            // 登录成功
            request.getSession().setAttribute("user", user);
            response.sendRedirect("/healthSelect");
        } else if (loginStatus == 3) {
            // root登录
            request.getSession().setAttribute("user", user);
            response.sendRedirect(request.getContextPath() + "/searchUser");
        } else if (loginStatus == 1) {
            // 用户名密码错误
            request.setAttribute("loginError", "用户名、密码或验证码错误！");
            request.getRequestDispatcher("pages/login.jsp").forward(request, response);
        } else if (loginStatus == 2) {
            // 验证码错误
            request.setAttribute("loginError", "验证码错误！");
            request.getRequestDispatcher("pages/login.jsp").forward(request, response);
        } else if (loginStatus == -1) {
            // 数据库抛异常
            request.setAttribute("loginError", "服务器发生错误");
            request.getRequestDispatcher("pages/login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}